<?php

namespace Plugins\IMApi\Service;

use Swoole\WebSocket\Server;

/**
 * 发送服务
 */
class SenderService
{
    private Server $server;
    private BindService $bindService;

    public function __construct(Server $server, BindService $service)
    {
        $this->server = $server;
        $this->bindService = $service;
    }

    public function sendToFd($fd, string $data): void
    {
        if ($this->server->isEstablished($fd)) {
            $this->server->push($fd, $data);
        }
    }


    public function sendToUserId(string $userId, string $data): void
    {
        foreach ($this->bindService->getUserFd($userId) as $fd) {
            $this->sendToFd($fd, $data);
        }
    }

    public function sendToRoom(int $roomId, string $data, array $ignoreUserIds = []): void
    {
        $roomUsers = $this->bindService->getRoomUsers($roomId);
        foreach ($roomUsers as $userId) {
            if (in_array($userId, $ignoreUserIds)) {
                continue;
            }
            $this->sendToUserId($userId, $data);
        }
    }

    public function sendAll(string $data, array $ignoreFds = []): void
    {
        foreach ($this->server->connections as $fd) {
            if(in_array($fd, $ignoreFds)){
                continue;
            }
            $this->sendToFd($fd, $data);
        }
    }
}